<template>
  <div class="main-info">
    <div class="content-container">
      <div class="tab-content" v-loading="operateLoading">
        <div class="filter-row">
          <div class="btn-warpper">
            <filter-form
              v-model="filterFormData"
              :batchNoList="batchNoList"
              :statusList="statusList"
              showBatchNo
              :showStatus="!isFireOrLogistics"
              @batchNoChange="getComLevel"
              @search="handleSearch"
              @refresh="refresh"
            />
          </div>
          <div class="com-status">{{ `${typeStatus[status]}` }}</div>
          <div class="action-buttons">
            <el-button
              class="button-search"
              v-if="['', 'end'].includes(status)"
              type="warning"
              @click="startDialogVisible = true"
              >开始比赛
            </el-button>
            <el-button
              class="button-search"
              v-if="
                !['', 'start', 'group', 'position'].includes(status) &&
                !isFireOrLogistics
              "
              type="primary"
              plain
              @click="viewMap"
              >查看对阵图
            </el-button>
            <el-button
              class="button-search"
              v-if="!['', 'end'].includes(status)"
              type="primary"
              plain
              @click="uploadImg"
              >上传底单
            </el-button>
            <!-- <el-button
              class="button-search"
              v-if="status == ‘group’"
              type="primary"
              plain
              @click="handleAddGroup"
              >添加小组赛
            </el-button> -->
            <el-button
              class="button-search"
              v-if="!['', 'start', 'end', 'final'].includes(status)"
              type="primary"
              @click="handleNextStep"
              >进入下阶段
            </el-button>
            <el-button
              class="button-search"
              v-if="['start', 'final'].includes(status)"
              type="primary"
              @click="endHandle"
            >
              比赛结束
            </el-button>
            <!-- 需要判断 阶段最后才显示 除了编程物流搬运 和 灭火挑战 不显示  -->
            <el-button
              v-if="status === 'end'"
              class="button-search"
              type="success"
              @click="handleExport"
              >导出Excel</el-button
            >
          </div>
        </div>
        <view-table
          v-model:currentPage="currentPage"
          v-loading="tableLoading"
          :table-data="tableData"
          :columns="tableColumns"
          :total="total"
          :operations="operations"
          :operation-width="operationWidth"
          @operation="handleTableOperation"
          @load-data="loadData"
        />
      </div>
    </div>

    <!-- 开始比赛 -->
    <start
      v-model:dialogVisible="startDialogVisible"
      :competition-type="activeTab"
      :group-category="filterFormData.groupCategory"
      @end="refresh"
    ></start>

    <!-- 登记分数对话框 -->
    <el-dialog title="登记分数" v-model="scoreDialogVisible" width="500px">
      <el-form :model="scoreForm" label-width="100px">
        <el-form-item label="基础项">
          <el-input-number v-model="scoreForm.basicScore" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="运动">
          <el-input-number
            v-model="scoreForm.sportsScore"
            :min="0"
            :max="100"
          />
        </el-form-item>
        <el-form-item label="编码">
          <el-input-number
            v-model="scoreForm.codingScore"
            :min="0"
            :max="100"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scoreDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleScoreSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 进入下阶段弹窗确认框 -->
    <el-dialog
      v-model="dialogNextVisible"
      :close-on-click-modal="false"
      title="进入下一阶段"
      width="500"
    >
      <div v-if="['', 'end'].includes(status)" class="next-text">
        是否开启小组循环赛？
      </div>
      <!-- <el-radio-group
        v-else-if="status === 'group'"
        v-model="competitionType"
      >
        <el-radio value="1">开启抢位赛阶段</el-radio>
        <el-radio value="2">开启淘汰赛阶段</el-radio>
      </el-radio-group> -->
      <div v-else-if="status === 'group' && isPosition">
        是否开启下轮抢位赛？
      </div>
      <div v-else-if="['position', 'group'].includes(status)" class="next-text">
        是否开启下轮淘汰赛？
      </div>
      <div v-else-if="status === 'knockout'" class="next-text">
        是否开启下轮淘汰赛？
      </div>
      <div v-else-if="status === 'thirdPlace'" class="next-text">
        是否开启决赛？
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="nextStepCancelHandle">取消</el-button>
          <el-button type="primary" @click="nextStepHandle"> 确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看/编辑分数对话框 -->
    <score-dialog
      v-model:dialogVisible="viewScoreDialogVisible"
      :writeable="scoreWriteable"
      :row="scoreDialogParams"
      :type="activeTab"
      :playType="type"
      :status="status"
      :knockoutRound="knockoutRound"
    />

    <!-- 调整场次顺序话框 -->
    <match-dialog
      v-model:modelValue="matchDialogVisible"
      :row="sortRow"
      :activeTab="activeTab"
      :playType="typeFieldMap[activeTab]"
      :batchNo="filterFormData.batchNo"
      :groupCategory="filterFormData.groupCategory"
      :status="sortRow.status || status"
      :selectStatus="filterFormData.status"
      :knockoutRound="knockoutRound"
      writeable
      @confirm="handleMatchConfirm"
    />

    <!-- 对阵图对话框 -->
    <el-dialog v-model="matchTreeVisible" title="对阵图" width="800px">
      <match-tree
        ref="treeRef"
        :activeTab="activeTab"
        :playType="typeFieldMap[activeTab]"
        :batchNo="filterFormData.batchNo"
        :groupCategory="filterFormData.groupCategory"
        @node-click="handleNodeClick"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import useAppStore from '@/store/modules/app.js'
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import scoreDialog from '@/components/scoreDialog.vue'
import viewTable from '@/components/viewTable.vue'
import matchDialog from '@/components/matchDialog.vue'
import matchTree from '@/components/matchTree.vue'
import filterForm from '@/components/filterForm.vue'
import start from '@/components/start.vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import { scoreEditColumnsConfig, typeFieldMap } from '@/config/type'
import { totalPoints } from '@/utils/calculateScore'
import {
  droneApi,
  fireApi,
  gobangApi,
  obstacleApi,
  logisticsApi,
  infoApi,
} from '@/api/modules'
import { typeStatus, typeMap } from '@/config/type'
import { getTime } from '@/config/rules'

const appStore = useAppStore()
watch(
  () => appStore.refreshFlag,
  (newVal) => {
    if (newVal) {
      loadData()
      appStore.setRefreshFlag(false)
    }
  }
)
const activeTab = computed(() => appStore.activeTab)
const isFireOrLogistics = computed(() => {
  return ['fire', 'logistics'].includes(activeTab.value)
})
const router = useRouter()
const filterFormData = ref({
  groupCategory: '小学组',
  studentInfo: '',
  regNo: '',
  batchNo: '',
  status: '',
})

let competitionType = ref(0)
const status = ref('')
const knockoutRound = ref(null)
const batchNoList = ref([])
const statusList = ref([
  { type: 'group', label: '小组赛' },
  { type: 'position', label: '抢位赛' },
  { type: 'knockout', label: '淘汰赛' },
  { type: 'thirdPlace', label: '季军赛' },
  { type: 'final', label: '决赛' },
])
const operationWidth = ref(215)
const operations = computed(() => {
  if (['', 'end'].includes(status.value)) {
    operationWidth.value = 80
    return [
      {
        name: 'history',
        label: '查看分数',
        type: 'primary',
        link: 'true',
        size: 'small',
      },
    ]
  }
  operationWidth.value = 215
  return [
    {
      name: 'history',
      label: '查看分数',
      type: 'primary',
      link: 'true',
      size: 'small',
    },
    {
      name: 'editMessage',
      label: '调整场次顺序',
      type: 'primary',
      link: 'true',
      size: 'small',
    },
    {
      name: 'editScore',
      label: '编辑分数',
      type: 'primary',
      link: 'true',
      size: 'small',
    },
  ]
})
// 添加提示信息内容
const helpText = `
比赛规则说明：

1. 小学组
- 适合6-12岁学生参加
- 比赛时长45分钟
- 特殊规则适用

2. 初中组
- 适合13-15岁学生参加
- 比赛时长60分钟
- 难度系数1.2

3. 高中组
- 适合16-18岁学生参加
- 比赛时长90分钟
- 难度系数1.5

注意事项：
• 参赛选手需提前15分钟到场
• 必须携带有效身份证件
• 严格遵守比赛纪律
• 如有特殊情况请提前说明
`

// 添加显示帮助弹窗的方法
const showHelpDialog = () => {
  ElMessageBox.alert(helpText, '比赛分组说明', {
    confirmButtonText: '我知道了',
    customClass: 'help-dialog',
    dangerouslyUseHTMLString: true,
  })
}
const apiHandle = {
  drone: droneApi,
  fire: fireApi,
  obstacle: obstacleApi,
  logistics: logisticsApi,
  gobang: gobangApi,
}

const total = ref(0)
const currentPage = ref(1)
const currentPageSize = ref(100)

const tableColumns = computed(() => {
  return scoreEditColumnsConfig[activeTab.value].filter((col) => !col.onlyEdit)
})
const fullScreenLoading = (text) => {
  return ElLoading.service({
    lock: true,
    text: text || '正在加载数据...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
}

const startDialogVisible = ref(false)
const scoreDialogVisible = ref(false)
const viewScoreDialogVisible = ref(false)
const scoreWriteable = ref(false)
const matchDialogVisible = ref(false)

watch(
  () => viewScoreDialogVisible.value,
  (newVal) => {
    if (!newVal && scoreWriteable.value) {
      refresh()
    }
  }
)
const matchTreeVisible = ref(false)

const tableData = ref([])
const getFinalTableData = async () => {
  tableLoading.value = true
  Promise.all([
    apiHandle[activeTab.value].queryPageList.post({
      pageNum: 1,
      pageSize: 2,
      playType: typeFieldMap[activeTab.value],
      batchNo: filterFormData.value.batchNo,
      ...filterFormData.value,
      status: 'final',
    }),
    apiHandle[activeTab.value].queryPageList.post({
      pageNum: 1,
      pageSize: 2,
      playType: typeFieldMap[activeTab.value],
      batchNo: filterFormData.value.batchNo,
      ...filterFormData.value,
      status: 'thirdPlace',
    }),
  ]).then((res) => {
    tableLoading.value = false
    if (res[0].code !== 200 || res[1].code !== 200) {
      ElMessage.error('获取数据失败')
      tableData.value = []
      return
    }
    tableData.value = res[0].data.list.concat(res[1].data.list).map((item) => {
      item.statusText = typeStatus[item.status]
      item.useTime = getTime(item.useTime)
      return item
    })
  })
}
const getTableData = async (params) => {
  if (status.value === 'final') {
    getFinalTableData()
    return
  }
  const newParams = {
    pageNum: currentPage.value,
    pageSize: currentPageSize.value,
    playType: typeFieldMap[activeTab.value],
    batchNo: filterFormData.value.batchNo,
    ...filterFormData.value,
  }
  if (
    status.value === 'knockout' &&
    filterFormData.value.status === 'knockout'
  ) {
    newParams.knockoutRound = knockoutRound.value
  }
  tableLoading.value = true
  const res = await apiHandle[activeTab.value].queryPageList.post(newParams)
  tableLoading.value = false
  if (res.code !== 200) {
    ElMessage.error('获取数据失败')
    tableData.value = []
    return
  }
  res.data.list.forEach((item) => {
    item.statusText = typeStatus[item.status]
    item.useTime = getTime(item.useTime)
    if ('obstacle' === activeTab.value) {
      item.points = totalPoints(item)
    }
    item.positionNoText = item.positionNo === -1 ? '轮空' : item.positionNo
  })
  tableData.value = res.data.list
  total.value = res?.data?.total || 0
}
const scoreForm = reactive({
  basicScore: 0,
  sportsScore: 0,
  codingScore: 0,
})

const tableLoading = ref(false)
const operateLoading = ref(false)

const endHandleConfirm = async () => {
  operateLoading.value = true
  // 先调取校验接口 校验分数是否全部录入 判断是否可以进行下一轮
  const params = {
    batchNo: filterFormData.value.batchNo,
    groupCategory: filterFormData.value.groupCategory,
    playType: typeFieldMap[activeTab.value],
    // istopfour为true 则是四强赛，校验冠军两人分数是否录入
    status: status.value,
    knockoutRound: knockoutRound.value,
  }
  //调取校验接口
  const checkRes = await apiHandle[activeTab.value].isInputSuccess.post(params)

  //判断校验接口返回的data 为false 则提示用户数据未完全录入
  if (checkRes.code !== 200 || checkRes.data === false) {
    operateLoading.value = false
    ElMessage.error('数据未完全录入，请录入分数后再进行操作!')
    return
  }
  if (status.value === 'final') {
    // 四强赛同时校验季军赛分数录入情况
    params.status = 'thirdPlace'
    const checkRes = await apiHandle[activeTab.value].isInputSuccess.post(
      params
    )

    //判断校验接口返回的data 为false 则提示用户数据未完全录入
    if (checkRes.code !== 200 || checkRes.data === false) {
      operateLoading.value = false
      ElMessage.error('数据未完全录入，请录入分数后再进行操作!')
      return
    }
  }

  //结束之前调用rankList接口
  const fileBlob = await apiHandle[activeTab.value].rankList.post(params)
  if (
    (!isFireOrLogistics.value && !(fileBlob instanceof Blob)) ||
    (isFireOrLogistics.value && fileBlob.code !== 200)
  ) {
    operateLoading.value = false
    ElMessage.error('排名失败,请重试!')
    return
  }
  const { batchNo, groupCategory } = filterFormData.value
  if (!['logistics', 'fire'].includes(activeTab.value)) {
    ElMessage.success('排名成功,排名Excel下载中!')
    download(
      fileBlob,
      `批次${batchNo}-${groupCategory}-${
        typeMap[typeFieldMap[activeTab.value]]
      }-比赛最终排名.xlsx`
    )
  }
  const res = await infoApi.end.post({
    playType: typeFieldMap[activeTab.value],
    batchNo: filterFormData.value.batchNo,
    groupCategory: filterFormData.value.groupCategory,
  })
  if (res.code !== 200) {
    ElMessage.error(res.message || '结束比赛失败')
    operateLoading.value = false
    return
  }
  status.value = 'end'
  operateLoading.value = false
  getComLevel(filterFormData.value.batchNo)
}
const endHandle = () => {
  ElMessageBox.confirm('是否确认结束比赛？', '结束比赛', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: true,
  })
    .then(() => {
      endHandleConfirm()
    })
    .catch(() => {})
}

let dialogNextVisible = ref(false)

const isPosition = ref(false)
const handleNextStep = async () => {
  if (status.value !== 'group') {
    // 如果是抢位赛或者淘汰赛 则直接进入下一轮
    dialogNextVisible.value = true
    return
  }
  // 如果是小组赛 则先判断是否可以进入抢位赛
  const loading = fullScreenLoading()
  try {
    const res = await apiHandle[activeTab.value].isPosition.post({
      playType: typeFieldMap[activeTab.value],
      batchNo: filterFormData.value.batchNo,
      groupCategory: filterFormData.value.groupCategory,
    })
    loading.close()
    if (res.code !== 200) {
      ElMessage.error(res.message || '获取数据失败')
      getTableData()
      return
    }
    isPosition.value = Boolean(res.data)
    dialogNextVisible.value = true
    currentPage.value = 1
  } catch (error) {
    loading.close()
    ElMessage.error('获取数据失败')
  }
}

const handleSearch = () => {
  nextTick(() => {
    currentPage.value = 1
    getTableData()
  })
}

const getComLevel = async (batchNo) => {
  // 获取比赛阶段并更新表格数据
  const newParams = {
    groupCategory: filterFormData.value.groupCategory,
    playType: type.value,
    batchNo: batchNo || '',
  }
  try {
    const res = await infoApi.competitionQuery.post(newParams)
    tableLoading.value = false
    if (res.code !== 200) {
      ElMessage.error('获取数据失败')
      tableData.value = []
      return
    }
    status.value = res?.data?.status || ''
    const copyStatus = status.value
    knockoutRound.value = res?.data?.knockoutRound
    if (Boolean(res?.data?.istopfour) && status.value === 'knockout') {
      status.value = 'final'
    }
    if (typeof knockoutRound.value !== 'number') knockoutRound.value = null
    // 请求到batchNo和比赛阶段后，直接改变filterFormData触发刷新页面
    filterFormData.value = {
      ...filterFormData.value,
      batchNo: batchNo || '',
      // copyStatus没有final状态，final会返回成knockout，比赛结束默认显示淘汰赛数据
      status: copyStatus === 'end' ? 'final' : copyStatus,
    }
    getTableData()
  } catch (error) {
    tableData.value = []
    tableLoading.value = false
    ElMessage.error('获取数据失败')
  }
}
const refresh = async (params) => {
  try {
    // 获取批次号列表
    const batchRes = await infoApi.getBatchNoList.post({
      playType: type.value,
      groupCategory: filterFormData.value.groupCategory,
    })
    if (batchRes.code !== 200) {
      ElMessage.error('获取数据失败')
      tableData.value = []
      return
    }
    batchNoList.value = batchRes.data || []
  } catch (error) {
    ElMessage.error('获取数据失败')
    tableData.value = []
  }
  if (batchNoList.value.length === 0) {
    tableData.value = []
    filterFormData.value.batchNo = batchNoList.value[0] || ''
    return
  }
  getComLevel(batchNoList.value[0])
}
const type = ref('1')
watch(
  () => activeTab.value,
  () => {
    type.value = typeFieldMap[activeTab.value]
    total.value = 0
    status.value = ''
    tableData.value = []
    currentPage.value = 1
    refresh()
  }
)

const nextStepHandle = async () => {
  // if (competitionType.value === 0) {
  //   ElMessage.warning('请选择下阶段比赛类型!')
  //   return
  // }
  const loading = fullScreenLoading()
  const params = {
    batchNo: filterFormData.value.batchNo,
    groupCategory: filterFormData.value.groupCategory,
    playType: typeFieldMap[activeTab.value],
    status: status.value,
    knockoutRound: knockoutRound.value,
  }
  // 先调取校验接口 校验分数是否全部录入 判断是否可以进行下一轮
  const checkRes = await apiHandle[activeTab.value].isInputSuccess.post(params)
  if (checkRes.code !== 200) {
    loading.close()
    dialogNextVisible.value = false
    ElMessage.error('数据未完全录入，请录入分数后再进行操作!')
    getTableData()
    return
  }
  operateLoading.value = true

  let apiType = 'positionNameList'
  let type = 'position'
  if (status.value === 'group' && isPosition.value) {
    // 当前状态是小组赛并且应该走抢位赛 走抢位赛接口
    apiType = 'positionNameList'
  } else if (['position', 'group'].includes(status.value)) {
    // 当前状态是抢位赛或者小组赛 走第一次淘汰赛接口
    apiType = 'knockoutNameList'
    type = 'knockout'
  } else if (status.value === 'knockout') {
    // 当前状态是淘汰赛 走下一步淘汰赛接口
    apiType = 'knockoutNextRound'
    type = 'knockout'
  }
  // 生成下阶段人员数据
  const res = await apiHandle[activeTab.value][apiType].post({
    playType: typeFieldMap[activeTab.value],
    batchNo: filterFormData.value.batchNo,
    groupCategory: filterFormData.value.groupCategory,
    status: status.value,
    knockoutRound: knockoutRound.value,
  })
  loading.close()
  dialogNextVisible.value = false
  if (res.code !== 200) {
    ElMessage.error(res.message || '获取数据失败')
    operateLoading.value = false
    getTableData()
    return
  }
  operateLoading.value = false
  filterFormData.value.status = type
  getComLevel(filterFormData.value.batchNo)
}
const nextStepCancelHandle = () => {
  dialogNextVisible.value = false
}

const handleNodeClick = (row) => {
  if (row.id === undefined) return
  console.log(row)
  viewScoreDialogVisible.value = true
  scoreDialogParams.value = row
  scoreWriteable.value = true
}

const handleAddGroup = () => {}
const treeRef = ref(null)
const viewMap = async () => {
  matchTreeVisible.value = true
  await nextTick()
  treeRef.value.getTreeData()
}

const uploadImg = () => {
  router.push({
    path: '/upload-image',
    query: {
      batchNo: filterFormData.value.batchNo,
      groupCategory: filterFormData.value.groupCategory,
      playType: typeFieldMap[activeTab.value],
      activeTab: activeTab.value,
      status: status.value,
    },
  })
}

const loadData = (params) => {
  currentPage.value = params.currentPage
  currentPageSize.value = params.pageSize
  getTableData()
}
const scoreDialogParams = ref({})
const historyHandler = async (row) => {
  scoreWriteable.value = false
  scoreDialogParams.value = row
  viewScoreDialogVisible.value = true
}
const sortRow = ref({})
const editMessageHandler = async (row) => {
  sortRow.value = row
  matchDialogVisible.value = true
}

const editScoreHandler = async (row) => {
  scoreWriteable.value = true
  scoreDialogParams.value = row
  viewScoreDialogVisible.value = true
}

const handleTableOperation = ({ name, row }) => {
  switch (name) {
    case 'history':
      historyHandler(row)
      break
    case 'editMessage':
      editMessageHandler(row)
      break
    case 'editScore':
      editScoreHandler(row)
      break
  }
}

const handleMatchConfirm = (data) => {
  matchDialogVisible.value = false
  getTableData()
}

const handleScoreSubmit = () => {
  // TODO: 实现分数提交逻辑
  ElMessage.success('分数登记成功')
  scoreDialogVisible.value = false
}

//导出excel
const handleExport = async () => {
  if (status.value !== 'end') {
    const params = {
      batchNo: filterFormData.value.batchNo,
      groupCategory: filterFormData.value.groupCategory,
      playType: typeFieldMap[activeTab.value],
      status: status.value,
      knockoutRound: knockoutRound.value,
    }
    // 先调取校验接口 校验通过再调用rank接口
    const checkRes = await apiHandle[activeTab.value].isInputSuccess.post(
      params
    )
    if (checkRes.code !== 200 || checkRes.data === false) {
      ElMessage.error(checkRes.message || '导出失败')
      return
    }
  }
  try {
    const res = await apiHandle[activeTab.value].export.post({
      batchNo: filterFormData.value.batchNo,
      groupCategory: filterFormData.value.groupCategory,
      playType: typeFieldMap[activeTab.value],
      // regNo: filterFormData.value.regNo,
      // status: status.value,
    })
    if (res) {
      // 下载Excel文件
      download(res, `${filterFormData.value.batchNo}.xlsx`)
      ElMessage.success('文件已开始下载')
    } else {
      ElMessage.error('下载失败：没有接收到数据')
    }
  } catch (error) {
    console.error('下载失败：', error)
    ElMessage.error('下载失败：' + error)
  }
}
// 兼容所有浏览器下载二进制文件
const download = (data, filename) => {
  try {
    if (!data) {
      console.error('下载失败：没有接收到数据')
      return
    }

    // 确保数据是Blob类型，并检查是否为Excel文件
    const blob =
      data instanceof Blob
        ? data
        : new Blob([data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          })

    // 验证文件大小，Excel文件不应该太小
    if (blob.size < 100) {
      // 小于100字节可能不是有效的Excel文件
      console.error('下载失败：文件大小异常，可能不是有效的Excel文件')
      ElMessage.error('下载失败：文件格式异常，请联系管理员')
      return
    }

    // IE浏览器使用msSaveOrOpenBlob API
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, filename)
      return
    }

    // 其他现代浏览器
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', filename)

    // 添加到DOM，触发下载，然后清理
    document.body.appendChild(link)
    link.click()

    // 下载启动后清理
    setTimeout(() => {
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url) // 释放URL对象
    }, 100)
  } catch (error) {
    console.error('文件下载失败:', error)
    ElMessage.error('文件下载失败，请稍后重试')
  }
}
// 组件挂载时触发
onMounted(() => {
  type.value = typeFieldMap[activeTab.value]
  refresh()
})
</script>

<style lang="scss" scoped>
.content-container {
  border-radius: 0;

  .table-custom {
    height: calc(100vh - 280px);

    :deep .el-scrollbar {
      max-height: calc(100vh - 362px);
      overflow-y: auto;
    }
  }
}
.com-status {
  background-color: #e6a23c;
  color: #fff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}
.filter-row {
  .action-buttons {
    padding-left: 10px;
    display: flex;
  }

  .btn-warpper {
    display: flex;

    .el-select {
      width: 100px;
      margin-right: 15px;
    }

    .el-input {
      width: 100px;
      margin-right: 15px;
    }
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.geometric-shape {
  position: absolute;
  opacity: 0.08;
  animation: float 20s infinite linear;

  &.hexagon {
    width: 100px;
    height: 115px;
    // background: #409eff;
    clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
    top: 15%;
    left: 10%;
    animation-duration: 15s;
  }

  &.circle {
    width: 80px;
    height: 80px;
    background: #67c23a;
    border-radius: 50%;
    top: 60%;
    right: 15%;
    animation-duration: 18s;
  }

  &.square {
    width: 70px;
    height: 70px;
    background: #e6a23c;
    transform: rotate(45deg);
    bottom: 20%;
    left: 20%;
    animation-duration: 20s;
  }

  &.triangle {
    width: 0;
    height: 0;
    border-left: 40px solid transparent;
    border-right: 40px solid transparent;
    border-bottom: 80px solid #f56c6c;
    top: 30%;
    right: 25%;
    animation-duration: 17s;
  }
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  50% {
    transform: translate(50px, 50px) rotate(180deg);
  }
  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.mt-4 {
  margin-top: 16px;
}
.help-button {
  margin-left: 8px;
  font-size: 18px;
  color: #909399;
  transition: all 0.3s;

  &:hover {
    color: #409eff;
    transform: scale(1.1);
  }
}

:deep(.help-dialog) {
  max-width: 500px;

  .el-message-box__content {
    padding: 20px;
    white-space: pre-line;
    line-height: 1.6;
    font-size: 14px;
  }

  .el-message-box__header {
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }
}
</style>
